import { request, Effect, history } from "umi";
import { login } from "./service";
import { token } from "@/util";
import type { Model, EffectsCommandMap } from 'dva';
import { ILogin } from "./data";

export interface IState {
  token: string,
  name: string,
  sex: string,
  age: string,
  address: string,
}

interface ILoginModel {
  namespace: string,
  state: IState,
  reducers: {
    signin: (state: IState, action: { token: string }) => IState,
    setName: (state: IState, action: { name: string }) => IState,
  }
  effects: {
    login: (action: { payload: ILogin }, effects: EffectsCommandMap) => Generator<any, void, { token: string }>
  }
}

const loginModel: ILoginModel = {
  namespace: 'login',
  state: {
    token: 'toekn',
    name: '',
    sex: '',
    age: '',
    address: ''
  },
  reducers: {
    signin: (state, action) => {
      return {
        ...state,
        token: action.token
      };
    },
    setName(state, action) {
      return {
        ...state,
        name: action.name
      };
    }
  },
  effects: {
    * login(action, { call, put, select }) {
      // const data = yield call(request, '/umi/login', {
      //   method: 'Post',
      //   data: {
      //     account: action.payload.account,
      //     password: action.payload.password,
      //   }
      // });
      const data = yield call(login, action.payload);
      token.setToken(data.token)
      yield put({
        type: 'signin',
        payload: data
      });
      history.push('/')
      location.reload()
    }
  }
}

export default loginModel